package com.example.yiparkapplication.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.example.yiparkapplication.R;
import com.example.yiparkapplication.activity.index.activity.ConvenientPaymentActivity.CarOrderNopayActivity;
import com.example.yiparkapplication.constant.API;
import com.example.yiparkapplication.constant.Constant;
import com.example.yiparkapplication.tool.CityDialog;
import com.example.yiparkapplication.util.ActivityCollector;
import com.example.yiparkapplication.util.BaseActivity;
import com.example.yiparkapplication.util.Common;
import com.example.yiparkapplication.util.MD5Utils;
import com.example.yiparkapplication.activity.index.activity.myCar.CarListAdapter;
import com.example.yiparkapplication.activity.index.activity.contactUs.ContactUsActivity;
import com.example.yiparkapplication.activity.index.activity.StaffQuery.StaffQueryActivity;
import com.example.yiparkapplication.activity.index.activity.ConvenientPaymentActivity.ConvenientPaymentActivity;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.BlockingDeque;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.example.yiparkapplication.constant.Constant.GET_NAME_CODE;

public class IndexActivity extends BaseActivity {

    private LinearLayoutManager layoutManager;
    private Handler handler = null;
    private static final int BAIDU_READ_PHONE_STATE = 100;
    private String mPhone;
    private String mName;
    private String mPassword;
    private String myCity;
    private String myProvince;
    private String mUserId;
    private TextView myLocation;
    private Intent intent;
    public BDLocationListener myListener = new IndexActivity.MyLocationListener();
    private boolean isFirstLoc = true;
    private String[] mCarNumberArr;
    private RecyclerView vRecyclerView;
    private boolean updateFlag = true; //是否跟新标记

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_center_layout);
        layoutManager = new LinearLayoutManager(this);
        handler = new Handler();

        if (Build.VERSION.SDK_INT > 9){
            /**
             *当前sdk版本大于9，安卓9.0以上的设备
             * 这个叫做严格模式的线程策略，还有一个vm策略来着。主要是检测比如线程读写时，那个步骤耗时太长，获取读写错误用的 */
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        if (Build.VERSION.SDK_INT >= 23){
            showContacts();
        }else{
            init();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == BAIDU_READ_PHONE_STATE){
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED){
                Toast.makeText(getApplicationContext(), "请授权定位功能", Toast.LENGTH_LONG).show();
            }
        }
        init();
    }

    public class MyLocationListener implements BDLocationListener{
        @Override
        public void onReceiveLocation(BDLocation location){
            if (isFirstLoc){
                isFirstLoc = false;
                String city = location.getCity();
                String province = location.getProvince();
                String provinceAndCIty = province+","+city;
                Common.getLocaCity(city);
                if (city == null || "".equals(city)){
                    Toast.makeText(IndexActivity.this, "未获取定位，部分功能无法使用", Toast.LENGTH_LONG).show();
                }else{
                    getNotification(provinceAndCIty, new Date().getTime());
                    myCity = city;
                    myProvince = province;
                    myLocation.setText(myCity);

                    SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                    editor.putString("myProvince", myProvince);
                    editor.putString("myCity", myCity);
                    editor.apply();
                }
            }
        }
    }

    private void getNotification(String location , long time){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_GET_NOTIFICATION + "?type=1" + "&location=" + location + "&time=" + time)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                Log.d("查询广告结果", "onResponse: " + joOut.toString());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    JSONObject object = joOut.getJSONObject("object");
                    if (object != null){
                        String url = object.getString("url");
                        if (url != null){
                            Looper.prepare();
                            Bitmap bitmap = Common.getHttpBitmap(url);
                            View view = View.inflate(IndexActivity.this, R.layout.fragment_coupon_action_layout, null);
                            //这一部分是使用插件弹窗显示广告来着，我试试原生有没有弹窗，不用第三方插件来的

                        }
                    }
                }
            }
        });
    }

    /**
     * 检查自身定位权限有没有获取*/
    private void showContacts(){
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
            ||ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            ||ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
            Toast.makeText(getApplicationContext(), "未获取定位，部分功能无法使用", Toast.LENGTH_LONG).show();
            ActivityCompat.requestPermissions(IndexActivity.this, new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE
            }, BAIDU_READ_PHONE_STATE);
        }else{
            init();
        }
    }

    private void init(){
        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        mPhone = pref.getString("phoneNumber", "");
        mPassword = pref.getString("password", "");
        if (myCity == null || "".equals(myCity)){
            myProvince = pref.getString("myProvince", "");
            myCity = pref.getString("myCity", "");
        }
        mUserId = pref.getString("userId", "");
        ImageView choseMyLocation = findViewById(R.id.id_chose_my_location);
        choseMyLocation.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                showDialog();
            }
        });
        myLocation = (TextView)findViewById(R.id.id_my_location);
        myLocation.setText(myCity);
        //个人中心设置
        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.id_personal_linearLayout);
        linearLayout.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                intent = new Intent(IndexActivity.this, UserInfoActivity.class);
                intent.putExtra("name", mName);
                intent.putExtra("phone", mPhone);
                startActivityForResult(intent, GET_NAME_CODE);
            }
        });

//        RelativeLayout mCar = findViewById(R.id.id_my_car);
        //便捷缴费
        LinearLayout convineientPayment = findViewById(R.id.id_convenient_payment);
        convineientPayment.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                intent = new Intent(IndexActivity.this, ConvenientPaymentActivity.class);
                startActivity(intent);
            }
        });
        //联系我们
        LinearLayout contactUs = findViewById(R.id.id_contact_us);
        contactUs.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                intent = new Intent(IndexActivity.this, ContactUsActivity.class);
                startActivityForResult(intent, Constant.GET_CONTACT_US_CODE);
            }
        });
        //车位导航
        LinearLayout carNavigation = findViewById(R.id.id_car_navigation);
        carNavigation.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                intent = new Intent(IndexActivity.this, CarNavigationActivity.class);
                startActivity(intent);
            }
        });

        //我的消费
        LinearLayout myConsume = findViewById(R.id.id_my_consume);
        myConsume.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                intent = new Intent(IndexActivity.this, MyConsumeActivity.class);
                intent.putExtra("userId", mUserId);
                startActivity(intent);
            }
        });

        //我的发票
        LinearLayout myInvoice = findViewById(R.id.id_my_invoice);
        myInvoice.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                intent = new Intent(IndexActivity.this, MyInvoiceActivity.class);
                intent.putExtra("userId", mUserId);
                startActivity(intent);
            }
        });

        //我的卡包
        LinearLayout myCarBag = findViewById(R.id.id_my_card_bag);
        myCarBag.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                intent = new Intent(IndexActivity.this, MyCardBagActivity.class);
                startActivity(intent);
            }
        });

        //陆巡查验
        LinearLayout staffQuery = findViewById(R.id.id_staff_query);
        staffQuery.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                intent = new Intent(IndexActivity.this, StaffQueryActivity.class);
                startActivity(intent);
            }
        });

        mapArgument();
        getUserDate();
        if (updateFlag){
            getVersionInfo();
        }

    }

    public void mapArgument(){
        //类实例创建
        LocationClient mLocationClient = new LocationClient(getApplicationContext());
        //给地图实例设置初始化参数
        mLocationClient.setLocOption(Common.initLocation());
        mLocationClient.registerLocationListener(myListener);
        mLocationClient.start();
    }

    /**
     * 获取用户数据*/
    private void getUserDate(){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_GET_USER_DATA + "?phoneNumber=" + mPhone + "&password=" + MD5Utils.md5Password(mPassword))
                .build();
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    JSONObject joIn = joOut.getJSONObject("object");
                    String name = joIn.getString("parkUserName");

                    if (name != null || !"".equals(name)){
                        mName = name;
                    }
                    new Thread(){
                        public void run(){
                            handler.post(runnableUi);
                        }
                    }.start();

                    String carNumberStr = joIn.getString("parkUserLicensePlate");
                    SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                    editor.putString("licensePlate", carNumberStr);
                    editor.apply();
                    if (carNumberStr != null || !"".equals(carNumberStr)){
                        mCarNumberArr = carNumberStr.split(",");
                        new Thread(){
                            public void run(){
                                handler.post(runnableCar);
                            }
                        }.start();
                    }else{
                        if (vRecyclerView != null){
                            new Thread(){
                                public void run(){
                                    handler.post(runnablNoView);
                                }
                            }.start();
                        }
                    }
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    }

    Runnable runnableUi = new Runnable(){
        @Override
        public void run(){
            TextView phoneTextView = findViewById(R.id.id_user_phone);
            phoneTextView.setText(mPhone);
            TextView nameTextView = findViewById(R.id.id_user_name);
            nameTextView.setText(mName);
        }
    };

    Runnable runnableCar = new Runnable(){
        @Override
        public void run(){
            vRecyclerView = findViewById(R.id.id_license_plate_recyclerView);
            vRecyclerView.setLayoutManager(layoutManager);
            CarListAdapter adapter = new CarListAdapter(mCarNumberArr, IndexActivity.this);
            vRecyclerView.setAdapter(adapter);
        }
    };

    Runnable runnablNoView = new Runnable(){
        @Override
        public void run(){
            vRecyclerView.setVisibility(View.GONE);
        }
    };

    private void getVersionInfo(){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_GET_CLIENT_VERSION + "?type=app")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplication());
                Log.d("获取版本信息", "onResponse: "+ joOut.toString());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    JSONObject object = joOut.getJSONObject("object");
                    if (object != null){
                        String mainVersion = object.getString("mainVersion");
                        final String url = object.getString("url");
                        String updateRecord = object.getString("updateRecord");
                        int coreVersion = object.getIntValue("coreVersion");
                        int versionCode = Common.packageCode(getApplicationContext());
                        String versionName = Common.packageName(getApplicationContext());
                        SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                        editor.putInt("coreVersion", coreVersion);
                        editor.putString("mainVersion", mainVersion);
                        editor.putString("url", url);
                        editor.putString("updateRecord", updateRecord);
                        editor.apply();

                        Looper.prepare();
                        if (!versionName.equals(mainVersion)){
//                            大更新
                            if (coreVersion > versionCode){
                                AlertDialog.Builder dialog = new AlertDialog.Builder(IndexActivity.this);
                                dialog.setTitle("新版本" + mainVersion);
                                dialog.setMessage("更新记录: \n\n" + updateRecord);
                                dialog.setPositiveButton("立即更新", new DialogInterface.OnClickListener(){
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i){
                                        Intent intent = new Intent(Intent.ACTION_VIEW);
                                        intent.setData(Uri.parse(url));
                                        startActivity(intent);
                                    }
                                });
                                dialog.setNegativeButton("退出", new DialogInterface.OnClickListener(){
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i){
                                        ActivityCollector.finishAll();
                                    }
                                });
                                dialog.setCancelable(false);
                                dialog.show();
                            }
                        }else{
//                            普通更新
                            AlertDialog.Builder dialog = new AlertDialog.Builder(IndexActivity.this);
                            dialog.setTitle("新版本" + mainVersion);
                            dialog.setMessage("更新记录：\n\n"+ updateRecord);
                            dialog.setPositiveButton("立即更新", new DialogInterface.OnClickListener(){
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i){
                                    updateFlag = false;
                                    Intent intent = new Intent(Intent.ACTION_VIEW);
                                    intent.setData(Uri.parse(url));
                                    startActivity(intent);
                                }
                            });
                            dialog.setNegativeButton("取消", new DialogInterface.OnClickListener(){
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i){
                                    updateFlag = false;
                                }
                            });
                            dialog.show();
                        }
                        Looper.loop();
                    }
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    };

    private void showDialog(){
        final CityDialog dialog = new CityDialog(this, myProvince+","+myCity);
        dialog.setCancelable(true);
        dialog.show();
        dialog.setClicklistener(new CityDialog.ClickListenerInterface(){
            @Override
            public void doConfirm(){
                myProvince = dialog.getProvince();
                myCity = dialog.getCity();
                dialog.dismiss();
                myLocation.setText(myCity);

                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putString("myProvince", myProvince);
                editor.putString("myCity", myCity);
                editor.apply();
            }
            @Override
            public void doCancel(){
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        switch(requestCode){
            case GET_NAME_CODE:
                if (resultCode == Constant.POST_NAME_CODE){
                    String parkUserName = data.getStringExtra("parkUserName");
                    TextView nameTextView = findViewById(R.id.id_user_name);
                    nameTextView.setText(parkUserName);
                    mName = parkUserName;
                }
                break;
            case Constant.GET_CONTACT_US_CODE:
                if (resultCode == Constant.POST_CONTACT_US_CODE){
                    //没啥东西
                };
                break;
            default:
                break;
        }
    }

    //跳转查询当前车单未完成扯淡页面
    public void toCarOrderNopayActivity(String carNumber){
        Intent intent = new Intent(IndexActivity.this, CarOrderNopayActivity.class);
        intent.putExtra("carNumber", carNumber);
        startActivity(intent);
    }

    //跳转车辆更多功能
    public void toCarMoreActivity(String carNumber){
        Intent intent = new Intent(IndexActivity.this, CarMoreActivity.class);
        intent.putExtra("carNumber", carNumber);
        intent.putExtra("userId", mUserId);
        startActivity(intent);
    }

    private boolean isQuit = false;

    @Override
    public void onBackPressed(){
        if (!isQuit){
            Toast.makeText(getApplicationContext(), "在按一次推出", Toast.LENGTH_LONG).show();
            isQuit = true;
            new Thread(new Runnable(){
                //单独分出一条线程，当按下第一次按钮之后的两秒种内没有按下第二下的话，就需要重新按两次，在两秒内按下第二次推出才算是确认推出
                @Override
                public void run(){
                    try {
                        Thread.sleep(2000);
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }finally{
                        isQuit = false;
                    }
                }
            }).start();
        }else{
            ActivityCollector.finishAll();
        }
    }

    @Override
    protected void onRestart(){
        super.onRestart();
        updateFlag = false;
        init();
    }

}
